package lesson27;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class MyDeadLock {
    
    private static Object o1 = new Object();

    private static Object o2 = new Object();

    public static void main(String[] args) {

        new Thread(() -> {
            synchronized (o1){
                try {
                    Thread.sleep(100);
                    synchronized (o2){
                        System.out.println(Thread.currentThread().getName() + "获取到了两把锁");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(() -> {
            synchronized (o2){
                try {
                    Thread.sleep(100);
                    synchronized (o1){
                        System.out.println(Thread.currentThread().getName() + "获取到了两把锁");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        long[] deadThreads = threadMXBean.findDeadlockedThreads();
        if(deadThreads != null && deadThreads.length > 0){
            for(int i = 0 ; i< deadThreads.length; i++){
                ThreadInfo threadInfo = threadMXBean.getThreadInfo(deadThreads[i]);
                System.out.println(threadInfo);
            }
        }
    }


}
